package com.marvels.common.utils;

import com.marvels.common.dto.ServerPropertiesDTO;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**服务Properties文件加载
 * @author hejie
 */
public class ServerProperties {
	/**
	 * 根据文件名存储加载不同的数据
	 */
	private static Map<String,ServerPropertiesDTO> propMaps = new HashMap<String, ServerPropertiesDTO>();
	private ServerProperties() {
		
	}
	/**通过key读取properties文件中的内容
	 * @param filePath   文件所在目录
	 * @param fileName   资源文件
	 * @param key        获取的key
	 * @return
	 */
	public static String getValue(String filePath,String fileName,String key) {
		ServerPropertiesDTO dto = propMaps.get(fileName);
		//未加载过
		boolean loadOk = false;
		if(dto == null) {
			loadOk = loadResource(filePath,fileName);
		}else {
			Date loadTime = dto.getLoadTime();
			Integer min = dto.getMin();
			boolean havLoad = calTime(loadTime, min);
			if(havLoad) {//需要重先加载
				loadOk = loadResource(filePath,fileName);
			}else {
				loadOk = true;
			}
		}
		if(loadOk) {
			dto = propMaps.get(fileName);
			return getValue(dto.getProp(),key);
		}else {
			return null;
		}
	}
	private static boolean loadResource(String filePath,String fileName) {
		InputStream is  = null;
		try {
			File loadFile = new File(filePath + File.separator + fileName);
			is = new FileInputStream(loadFile);
			ServerPropertiesDTO dto = new ServerPropertiesDTO();
			dto.setFileName(fileName);
			dto.getProp().load(is);
			String timeMin = dto.getProp().getProperty("resource.load.time");
			dto.setMin(timeMin);
			propMaps.put(fileName, dto);
			return true;
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("加载文件出错",e);
		} finally {
			if(is!=null) {
				try {
					is.close();
				} catch (IOException e) {
					MarvelsLogUtil.getInstance().error("加载文件关闭错误",e);
				}
			}
		}
		return false;
	}
	private static boolean calTime(Date loadTime,Integer min) {
		if(min == null) {//默认分钟
			min = 5;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(loadTime);
		cal.add(Calendar.MINUTE, min);
		Calendar nowCal = Calendar.getInstance();
		return nowCal.compareTo(cal)>0;
//		return false;
	}
	private static String getValue(Properties prop,String key) {
		//init
		return prop.getProperty(key);
	}
	public static void main(String args[]) {
		String xx = ServerProperties.getValue("D:\\iwork\\需求文档汇总\\支付宝二维码支付\\", "application.properties", "spring.datasource.url");
		System.out.println(xx);
	}
}
